package com.sjb.cp.manager.websocket.disruptor;

import cn.hutool.json.JSONUtil;
import com.lmax.disruptor.WorkHandler;
import com.sjb.cp.manager.websocket.PictureEditHandler;
import com.sjb.cp.manager.websocket.PictureEditRequestMessage;
import com.sjb.cp.manager.websocket.PictureEditResponseMessage;
import com.sjb.cp.model.enums.PictureEditMessageTypeEnum;
import com.sjb.cp.model.po.User;
import com.sjb.cp.service.UserService;
import groovy.lang.Lazy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * @Author:sjb
 * @CreateTime:2025-02-20
 * @Description: 定义时间处理器-消费者
 * @Version：1.0
 */
@Slf4j
@Component
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {


    @Resource
    @Lazy
    private PictureEditHandler pictureEditHandler;

    @Resource
    private UserService userService;

    @Override
    public void onEvent(PictureEditEvent event) throws Exception {
        // 将消息解析为PictureEditMessage
        PictureEditRequestMessage pictureEditRequestMessage = event.getPictureEditRequestMessage();
        WebSocketSession session = event.getSession();
        String type = pictureEditRequestMessage.getType();
        PictureEditMessageTypeEnum pictureEditMessageTypeEnum = PictureEditMessageTypeEnum.valueOf(type);

        Long pictureId = (Long) session.getAttributes().get("pictureId");
        User user = (User)session.getAttributes().get("user");

        // 调用对应的消息处理方法
        switch (pictureEditMessageTypeEnum){
            case ENTER_EDIT:
                pictureEditHandler.handleEditMessage(pictureEditRequestMessage,session,user,pictureId);
                break;
            case EDIT_ACTION:
                pictureEditHandler.handleEditActionMessage(pictureEditRequestMessage,session,user,pictureId);
                break;
            case EXIT_EDIT:
                pictureEditHandler.handleExitEditMessage(pictureEditRequestMessage,session,user,pictureId);
                break;
            default:
                PictureEditResponseMessage pictureEditResponseMessage = new PictureEditResponseMessage();
                pictureEditResponseMessage.setType(PictureEditMessageTypeEnum.ERROR.getValue());
                pictureEditResponseMessage.setMessage("消息类型错误");
                pictureEditResponseMessage.setUserVo(userService.getUserVo(user));
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditResponseMessage)));
        }
    }
}
